<?php
namespace User\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\ServiceManager\ServiceManager;

class UserInRoleTable {
	
	protected $tableGateway;
	protected $serviceManager;
	
	public function __construct(TableGateway $tableGateway, ServiceManager $serviceManager)
	{
		$this->tableGateway = $tableGateway;
		$this->serviceManager = $serviceManager;
	}
	
	/**
	 * @return the $tableGateway
	 */
	public function getTableGateway() {
		return $this->tableGateway;
	}

	/**
	 * @param TableGateway $tableGateway
	 */
	public function setTableGateway($tableGateway) {
		$this->tableGateway = $tableGateway;
	}

	/**
	 * @return the $serviceManager
	 */
	public function getServiceManager() {
		return $this->serviceManager;
	}

	/**
	 * @param ServiceManager $serviceManager
	 */
	public function setServiceManager($serviceManager) {
		$this->serviceManager = $serviceManager;
	}

	public function fetchAll()
	{
		$roleTable = $this->serviceManager->get('User\Model\RoleTable');
		$userTable = $this->serviceManager->get('User\Model\UserTable');
		
		$result = $this->tableGateway->select()->toArray();
		
		for($i = 0; $i < count($result); $i++)
		{
			$userSel = new \Zend\Db\Sql\Select();
			$userSel->from('users');
			$userSel->columns(array('username', 'first_name', 'middle_name', 'last_name'));
			$userSel->where(array('id' => $result[$i]['uid']));
			$userResultSet = $userTable->getTableGateway()->selectWith($userSel);
			$userRow = $userResultSet->current();
			
			$roleResultSet = $roleTable->getTableGateway()->select(array('rid' => $result[$i]['rid']));
			$roleRow = $roleResultSet->current();
			
			$result[$i]['username'] = $userRow->getUsername();
			$result[$i]['fullname'] = $userRow->getLast_name() . ' ' . $userRow->getMiddle_name() . ' ' . $userRow->getFirst_name();
			$result[$i]['role_name'] = $roleRow['name'];
		}
		
		return $result;
	}
	
	public function save($data)
	{
	
		$saveArr = array('rid' => $data['rid']);
	
		$uid = (int)$data['uid'];

		$where = new \Zend\Db\Sql\Where();
		
		$where->equalTo('uid', $uid);
		
		$this->tableGateway->update($saveArr, $where);
		
	}
	
	public function addNew($data)
	{
		$this->tableGateway->insert($data);	
	}
	
	
	public function reset($uid)
	{
		$roleTable = $this->serviceManager->get('User\Model\RoleTable');
		$where = new \Zend\Db\Sql\Where();
		$where->equalTo('key', 'authenticated');
		$resultSet = $roleTable->getTableGateway()->select($where);
		$row = $resultSet->current();
		
		$this->save(array('uid' => intval($uid), 'rid' => $row['rid']));
	}
	
	public function getById($uid)
	{
		$result = $this->tableGateway->select(array('uid' => intval($uid)))->current();
		
		return $result;
	}
}

?>